package com.javajun.endofterm.controller.api_v1;

import com.javajun.endofterm.common.AjaxUtils;
import com.javajun.endofterm.common.DataGridParam;
import com.javajun.endofterm.common.DataGridUtils;
import com.javajun.endofterm.entity.Domitory;
import com.javajun.endofterm.entity.Student;
import com.javajun.endofterm.entity.SysRole;
import com.javajun.endofterm.service.DomitoryService;
import com.javajun.endofterm.service.StudentService;
import com.javajun.endofterm.service.SysRoleService;
import com.javajun.endofterm.web.form.StudentForm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashSet;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-12-04-12:42 上午
 */
@RequestMapping("/api-v1/student")
@RestController
public class StudentController{

    @Autowired
    private StudentService studentService;

    @Autowired
    private DomitoryService domitoryService;

    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/page")
    public Object page(DataGridParam param) {
        if (param.getLimit() == null) {
            param.setLimit(15);
        }
        if (param.getPage() == null) {
            param.setPage(1);
        }
        Sort sort = Sort.by("id");
        Pageable pageable = param.getPageable(sort);
        Page<Student> page = studentService.findAll(pageable);
        return DataGridUtils.buildResult(page);
    }

    @RequestMapping(value = "/search")
    public Object search(DataGridParam param, String keyword) {
        Sort sort = Sort.by("username"); // 按照学号顺序排列
        Pageable pageable = param.getPageable(sort);
        Specification<Student> spec = buildSpec(keyword);
        Page<Student> page = studentService.findAll(spec, pageable);
        return DataGridUtils.buildResult(page);
    }

    /**
     * 动态安全查询
     * @param keyword
     * @return Specifitation<Stduent>
     */
    public Specification<Student> buildSpec(String keyword) {
        Specification<Student> spec = new Specification<Student>() {

            private static final long serialVersionUID = 3245024417754333760L;

            @Override
            public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules=new HashSet<>();
                if (StringUtils.hasText(keyword)) {
                    Predicate p1 = cb.like(root.get("username"), "%"+keyword+"%");
                    Predicate p2 = cb.like(root.get("name"), "%"+keyword+"%");
                    Predicate p3 = cb.like(root.get("email"), "%"+keyword+"%");
                    Predicate p4 = cb.like(root.get("phone"), "%"+keyword+"%");
                    Predicate p5 = cb.like(root.get("domitory").get("name"), "%"+keyword+"%");
                    Predicate p6 = cb.like(root.get("department"), "%"+keyword+"%");
                    Predicate p7 = cb.like(root.get("majorClazz"), "%"+keyword+"%");
                    Predicate or = cb.or(p1, p2, p3, p4, p5, p6, p7);
                    rules.add(or);
                }

                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        return  spec;
    }

    @RequestMapping("/add")
    public Object addStudent(@RequestBody StudentForm form) {
        Domitory domitory = domitoryService.findById(form.getDomitoryId());
        Student student = new Student();
        BeanUtils.copyProperties(form, student);
        student.setDomitory(domitory);
        //todo 设置初始密码
        SysRole role = sysRoleService.findByName("学生");
        List<SysRole> roleList = student.getSysRoleList();
        roleList.add(role);
        student.setSysRoleList(roleList);
        student.setPassword(new BCryptPasswordEncoder().encode("1111"));
        studentService.save(student);
        return AjaxUtils.buildResult("添加学生成功");
    }

    @RequestMapping(value = "/edit")
    public Object editStudent(@RequestBody StudentForm form) {
        System.out.println(form);
        Student student = studentService.findById(form.getId());
        BeanUtils.copyProperties(form, student);
        Domitory domitory = student.getDomitory();
        domitory.getStudentList().remove(student);
        domitoryService.save(domitory);
        studentService.save(student);
        return AjaxUtils.buildResult("修改成功");
    }

    @RequestMapping(value = "/delete")
    public Object deleteStudent(Integer id) {
        studentService.deleteById(id);
        return AjaxUtils.buildResult("删除成功");
    }
}
